﻿@using Snow.Blog.Service.Dto;
@using Snow.Blog.Service.Bloggers.Dto;
@inject Snow.Blog.Service.Bloggers.IBloggerService BloggerService
<div class="list-group">
    @if (bloggers != null)
    {
        foreach (var item in bloggers.Items)
        {
            <div class="list-group-item">
                <a href="/blogger/@item.Id" target="_blank">
                    <h3 class="mb-4" title="@item.Title">@item.Title</h3>
                </a>
                <div class="d-flex w-100 justify-content-between">
                </div>
                <p class="mb-1">@item.Description</p>
                <small><i class="far fa-calendar-alt"></i>@item.LastModifyDate</small>
                <small><i class="fas fa-tag"></i>@item.CategoryName</small>
            </div>
        }
        <Pager Page="Page"
               PageCount="pageCount"
               HrefUrl="@pageUrl" />
    }
</div>
@code {
    private PagedResultDto<BloggerListDto> bloggers;

    [Parameter]
    public int Page { get; set; } = 1;
    [Parameter]
    public int? CategoryId { get; set; }
    [Parameter]
    public string Keyword { get; set; }

    private int limit = 2;
    private int pageCount;
    private string pageUrl;
    private bool isInit = false;

    protected override async Task OnInitializedAsync()
    {
        await ResetParemeterAsync();
        isInit = true;
    }
    /// <summary>
    /// 父元素设置参数后的回调
    ///</summary>
    /// <returns></returns>
    protected override async Task OnParametersSetAsync()
    {
        await ResetParemeterAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await Task.Run(() =>
            {
                isInit = false;

            });
        }
    }

    /// <summary>
    /// 重置参数
    /// </summary>
    /// <returns></returns>
    private async Task ResetParemeterAsync()
    {
        if (!isInit)
        {
            pageUrl = CreatePageUrl();
            bloggers = await GetBloggersAsync(Page);
            pageCount = bloggers.PageCount;
        }
    }

    /// <summary>
    /// 创建分页Url
    /// </summary>
    /// <returns></returns>
    private string CreatePageUrl()
    {
        string url = String.Empty;
        if (!String.IsNullOrEmpty(Keyword))
        {
            url += "/search/" + Keyword;

        }
        if (CategoryId.HasValue)
        {
            url += $"/{CategoryId.Value}";
        }
        url += $"/#Page";
        return url;
    }

    /// <summary>
    ///获取博客列表
    /// </summary>
    /// <param name="page">页码</param>
    /// <returns></returns>
    private async Task<PagedResultDto<BloggerListDto>> GetBloggersAsync(int page)
    {
        return await BloggerService.GetBloggersPagedAsync(new GetBloggerInput()
        {
            Page = page,
            CategoryId = CategoryId,
            Limit = limit,
            Title = Keyword
        });
    }
}